package cn.sdhuijin.vms.controller;

import java.util.List;

import javax.inject.Inject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.sdhuijin.vms.controller.comand.PageInfo;
import cn.sdhuijin.vms.controller.comand.UserCommand;
import cn.sdhuijin.vms.model.User;
import cn.sdhuijin.vms.realm.ShiroDbRealm;
import cn.sdhuijin.vms.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Inject
	private IUserService userService;

	@RequiresRoles("admin")
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String show() {
		return "user/show";
	}

	@RequiresRoles("admin")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(PageInfo pageInfo, Model model) {
		Page<User> page = userService.getList(pageInfo.getPage(),
				pageInfo.getRows());
		model.addAttribute("page", page);
		return "user/list";
	}

	@RequiresRoles("admin")
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@ModelAttribute User user) {
		return "user/add";
	}

	@RequiresRoles("admin")
	@RequestMapping(value = { "/add" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult add(@Validated User user, BindingResult error) {
		JsonResult jr = new JsonResult();
		StringBuffer sb = new StringBuffer();
		if (error.hasErrors()) {
			jr.setSuccess(false);
			List<FieldError> fes = error.getFieldErrors();
			for (FieldError fe : fes) {
				sb.append(fe.getDefaultMessage()).append(" ");
			}
		} else {
			user.setPassword(ShiroDbRealm.encryptPassword("123456"));
			userService.save(user);
		}
		jr.setMessage(sb.toString());
		return jr;
	}

	@RequiresUser
	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public String update(Model model) {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		user = userService.load(user.getId());
		model.addAttribute(user);
		return "user/update";
	}

	@RequestMapping(value = { "/update" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult update(@Validated UserCommand user, BindingResult error) {
		JsonResult jr = new JsonResult();
		StringBuffer sb = new StringBuffer();
		if (error.hasErrors()) {
			jr.setSuccess(false);
			List<FieldError> fes = error.getFieldErrors();
			for (FieldError fe : fes) {
				sb.append(fe.getDefaultMessage()).append(" ");
			}
		} else {
			User temp = (User) SecurityUtils.getSubject().getPrincipal();
			temp = userService.load(temp.getId());
			temp.setPhone(user.getPhone());
			temp.setRealname(user.getRealname());
			userService.save(temp);
		}
		jr.setMessage(sb.toString());
		return jr;
	}

	@RequiresRoles("admin")
	@RequestMapping(value = { "/delete/{userId}" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult delete(@PathVariable Long userId) {
		JsonResult jr = new JsonResult();
		jr.setSuccess(true);
		try {
			userService.delete(userId);
		} catch (Exception e) {
			jr.setMessage(e.getMessage());
			jr.setSuccess(false);
		}
		return jr;
	}

	@RequiresRoles("admin")
	@RequestMapping(value = { "/resetPassword/{userId}" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult resetPassword(@PathVariable Long userId) {
		JsonResult jr = new JsonResult();
		jr.setSuccess(true);
		try {
			User user = userService.load(userId);
			user.setPassword(ShiroDbRealm.encryptPassword("123456"));
			userService.save(user);
		} catch (Exception e) {
			jr.setMessage(e.getMessage());
			jr.setSuccess(false);
		}
		return jr;
	}

	@RequiresUser
	@RequestMapping(value = "/changePwd", method = RequestMethod.GET)
	public String changePwd() {
		return "user/changePwd";
	}

	@RequiresUser
	@RequestMapping(value = { "/changePwd" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult changePwd(String pwd, String planPwd) {
		JsonResult jr = new JsonResult();
		jr.setSuccess(true);
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		user = userService.load(user.getId());
		if (ShiroDbRealm.validatePassword(pwd, user.getPassword())) {
			user.setPassword(ShiroDbRealm.encryptPassword(planPwd));
			userService.save(user);
		} else {
			jr.setMessage("老密码不正确。");
			jr.setSuccess(false);
		}
		return jr;
	}

}
